22.03.17 - Parametric Polymorphism and Boxing
Can initialise an array as size 0, then create a new array with required size, copy data from the initial array, then overwrite the initial array with the new array
public class ArrayInt
{
private int size = 0;
private int[] data = new int[0];
public void add( int val )
{
int[] newData = new int[size+1];
if ( size > 0 )
System.arraycopy( data, 0, newData, 0, size);
newData[size] = val;
size++;
data = newData;
}
}
Parametric Polymorphism
- Most OO languages support this. Can use parametric polymorphism to make a generic class which can store ANY type of data
- One type which is parameterised on another type
Better way for a generic class
- Parameterise the original class to avoid having to create different types but still check the types at COMPILE time. Need to say which type it stores when creating the object.
- Add
<T>
after the class name - Change types from
int
toT
throughout
The problems
Type Erasure
- Type exists at compile time, but not at runtime.
- Type is 'erased' at compile time so runtime sees it as some base-class type(Object)
- This causes an issue as cannot write code which needs to know the real type at runtime.
- To fix this can use the base class as it IS-AN Object, so create an array of objects instead
Extracting the data
- Want a T and have an array objects, problem was caused by using Object instead of T
- To resolve this, can safely cast the object - because we know they are all of type T, from when we stored them
Basic Data Types
- int, bool , float, etc are NOT classes
- For each basic data type there is a wrapper class, which will wrap up the data in an object.
- Boxing: wrapping up a data type in an object
- Unboxing: extracting the data again
- Auto-boxing: automatically doing this
Autoboxing
- Whenever an object is needed, you have a basic data type, the compiler will create the code to convert to the wrapper class automatically
- Due to this, in many cases can treat basic data types as if they are objects
Summary
- Can create classes which are generic
- This is Parametric Polymorphism
- Can create instances of a class which work with a specific other class
- The class has to do exactly the same thing regardless of the actual class
- The class will not be known at runtime
- You CAN use the class type at compile time.